package com.example.a90419.audio;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.AsyncTask;
import android.util.Log;

import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingDeque;

public class XFAudioPlay {

    private static final String TAG = "XFAudioPlay";

    public AudioTrack track = null;// 录音文件播放对象
    private int frequence = 8000;// 采样率 8000
    private int channelInConfig = AudioFormat.CHANNEL_OUT_MONO;// 定义采样通道
    private int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;// 定义音频编码（16位）
    private int bufferSize = -1;// 播放缓冲大小
    private boolean isPlaying = false;
  //  private LinkedBlockingDeque<byte[]> deque = new LinkedBlockingDeque<>();
    private LinkedList<byte[]> queue = new LinkedList<>();
    private Thread task;
    private byte[] temp = new byte[800*10];
    private int k = 0;

    public XFAudioPlay() {
        init();
    }


    public void init() {
        // 获取缓冲 大小
        bufferSize = AudioTrack.getMinBufferSize(frequence, channelInConfig,
                audioEncoding);
// 实例AudioTrack
        track = new AudioTrack(AudioManager.STREAM_MUSIC, frequence,
                channelInConfig, audioEncoding, bufferSize,
                AudioTrack.MODE_STREAM);
        track.setStereoVolume(AudioTrack.getMaxVolume(),
                AudioTrack.getMaxVolume());
    }


    public void play() {
        if (null != track) {
            track.play();
        }
    }

    public void stop() {
        if (null != track) {
            isPlaying = false;
           // track.stop();
        }
        task = null;
    }

    public void destroy() {
        if (null != track) {
            track.release();
            track = null;
        }
        if (null!=queue)
        queue.clear();
        task = null;
    }


    public void add(byte[] bytes) {
        if (null == bytes) return;
        if (!isPlaying){
            task = new Thread(mission);
            task.start();
            isPlaying = true;
        }

        try {
            for (int i=0;i<bytes.length;i++){ //将字节流进行缓冲  达到一定值再输出
                if (k==temp.length){
                    queue.add(temp);
                    temp = new byte[8000];
                    k=0;
                    Log.e(TAG, "add:  temp的SIZE为："+queue.size());
                }

                temp[k] = bytes[i];

                k++;
            }

           // deque.putLast(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private Runnable mission = new Runnable() {
        @Override
        public void run() {
            //    try {

                    while (isPlaying){
                        if (queue.size()>0) {
                            byte[] bytes = queue.getFirst(); //阻塞的 当为空的时候是阻塞的
                            track.write(bytes, 0, bytes.length);
                            Log.e(TAG, "run: 队列大小:" + queue.size());
                                queue.removeFirst();

                        }else {
                            //stop();
                        }
                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    Log.e(TAG, "doInBackground: 队列阻塞异常 "+ e);
//                    queue.clear();
//                    queue = new LinkedList<>(); //尝试清空重新申请
//                }

        }
    };



}
